import pandas as pd
from sklearn.cluster import KMeans

def k_means(file_in, file_out):
    k = 300  # 需要进行的聚类类别数
    reader = pd.read_csv(file_in)   # 读取经纬度数据
    X = pd.DataFrame(reader[['longitude', 'latitude']])    # 调用k-means算法，进行聚类
    kmodel = KMeans(n_clusters=k, n_jobs=-1)  # n_jobs是并行数，一般等于CPU数较好
    kmodel.fit(X)  # 训练模型
    r1 = pd.Series(kmodel.labels_).value_counts()  # 统计各个类别的数目
    r2 = pd.DataFrame(kmodel.cluster_centers_)  # 找出聚类中心
    r = pd.concat([r2, r1], axis=1)  # 横向连接（0是纵向），得到聚类中心对应的类别下的数目
    r.columns = list(X.columns) + [u'num']  # 重命名表头

    frame = pd.DataFrame(columns=r.columns, data=r)
    frame = pd.DataFrame(frame, columns=['longitude', 'latitude', 'num', 'weight'])
    all_num = frame['num']
    frame['weight'] = frame.apply(lambda x: weighing(x.num, all_num), axis=1)  # 计算权重
    del frame['num']  # 删除聚类点一列
    print(frame)
    frame.to_csv(file_out, index=0)


# 权重划分
def weighing(num, num_sum):
    quantile_20 = num_sum.quantile(0.2)
    quantile_40 = num_sum.quantile(0.4)
    quantile_60 = num_sum.quantile(0.6)
    quantile_80 = num_sum.quantile(0.8)
    if num < quantile_20:
        return 0
    elif quantile_20 <= num < quantile_40:
        return 1
    elif quantile_40 <= num < quantile_60:
        return 2
    elif quantile_60 <= num < quantile_80:
        return 3
    elif num >= quantile_80:
        return 4



if __name__ == '__main__':
    time_ = [['00-00', '01-00'],
             ['01-00', '02-00'],
             ['02-00', '03-00'],
             ['03-00', '04-00'],
             ['04-00', '05-00'],
             ['05-00', '06-00'],
             ['06-00', '07-00'],
             ['07-00', '08-00'],
             ['08-00', '09-00'],
             ['09-00', '10-00'],
             ['10-00', '11-00'],
             ['11-00', '12-00'],
             ['12-00', '13-00'],
             ['13-00', '14-00'],
             ['14-00', '15-00'],
             ['15-00', '16-00'],
             ['16-00', '17-00'],
             ['17-00', '18-00'],
             ['18-00', '19-00'],
             ['19-00', '20-00'],
             ['20-00', '21-00'],
             ['21-00', '22-00'],
             ['22-00', '23-00'],
             ['23-00', '00-00']]
    for i in range(5, 8):
        for j in range(0, 24):
            file_in = '..\\data\\divide_time\\week_' + str(i) + '\\time ' + time_[j][0] + '~' + time_[j][
                1] + '.csv'
            file_out = '..\\data\\after_K-means\\week_' + str(i) + '\\time ' + time_[j][0] + '~' + time_[j][
                1] + '.csv'
            k_means(file_in, file_out)
